package com.yihusitian.zsxq.sg.util;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @Description JAXB实现JAVA对象和XML字符串的互相转换
 * @Author LeeHo
 * @Date 2020/8/26 13:57
 */
public class JAXBUtil {

	private JAXBUtil() {
	}

    /**
     * 将JAVA对象转换为XML
     *
     * @param obj
     * @return
     * @throws JAXBException
     * @throws IOException
     */
	public static String toXML(final Object obj) throws JAXBException, IOException {
		final StringWriter stringWriter = new StringWriter();
		final JAXBContext context = JAXBContext.newInstance(obj.getClass());
		final Marshaller marshaller = context.createMarshaller();
		// 格式化xml输出的格式
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		marshaller.marshal(obj, stringWriter);
		final String xml = stringWriter.toString();
		stringWriter.close();
		return xml;
	}

    /**
     * 将XML转换为JAVA对象
     *
     * @param clazz
     * @param xml
     * @param <T>
     * @return
     * @throws Exception
     */
	public static <T> T fromXML(final Class<T> clazz, final String xml) throws Exception {
		final JAXBContext context = JAXBContext.newInstance(clazz);
		final Unmarshaller unmarshaller = context.createUnmarshaller();
		final StringReader reader = new StringReader(xml);
		// 忽略命名空间的解析xml
		final SAXParserFactory sax = SAXParserFactory.newInstance();
		sax.setNamespaceAware(false);
		final XMLReader xmlReader = sax.newSAXParser().getXMLReader();
		final Source source = new SAXSource(xmlReader, new InputSource(reader));
		final Object object = unmarshaller.unmarshal(source);
		return (T) clazz.cast(object);
	}

}
